<?php

namespace app\service;

use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Lang;

class EmailService
{
    /**
     * 发送邮件验证码
     *
     * @param string $email 邮箱地址
     * @param string $code  验证码
     *
     * @return bool|string 成功返回true，失败返回错误信息
     */
    public static function sendCode($email, $code)
    {
        $mail = new PHPMailer(true);

        try {
            $mailConfig = config('app.email');

            // 服务器设置
            $mail->isSMTP();
            $mail->Host = $mailConfig['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $mailConfig['username'];
            $mail->Password = $mailConfig['password'];
            $mail->SMTPSecure = $mailConfig['secure'];
            $mail->Port = $mailConfig['port'];
            $mail->CharSet = 'UTF-8';

            // 收发人设置
            $mail->setFrom($mailConfig['from_email'], $mailConfig['from_name']);
            $mail->addAddress($email);

            // 内容设置
            $mail->isHTML(true);
            $mail->Subject = Lang::get('email_verification_code_subject');
            $mail->Body = str_replace('{code}', $code, Lang::get('email_verification_code_body_html'));
            $mail->AltBody = str_replace('{code}', $code, Lang::get('email_verification_code_body_plain'));

            $mail->send();

            return true;
        } catch (Exception $e) {
            return "邮件发送失败: {$mail->ErrorInfo}";
        }
    }
}
